package cn.cxyxj.code_auth_jwt_persistence_prod.auth.handler;


import cn.cxyxj.code_auth_jwt_persistence_prod.common.ApiResult;
import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUserDetails;
import cn.cxyxj.code_auth_jwt_persistence_prod.utils.JwtUtil;
import cn.cxyxj.code_auth_jwt_persistence_prod.utils.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功回调
 */
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 登录成功，返回json格式
        SysUserDetails principal = (SysUserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        String token = JwtUtil.createToken(username);
        // 保存到 Redis 中，并设置过期时间为 2 小时
        RedisUtil.set(String.format("token:%s" , token), JSONObject.toJSONString(principal),2, TimeUnit.HOURS);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().println(JSONObject.toJSONString(ApiResult.success(token)));
        // request.getRequestDispatcher("http://localhost:8091/oauth/authorize?client_id=client-a&response_type=code&scope=all&redirect_uri=http://baidu.com&Authorization=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkZXYiLCJleHAiOjE2NzcxMzAxMzYsImlhdCI6MTY3NzEyOTEzNiwiYWNjb3VudCI6ImRldiIsImp0aSI6IjU1N2JhMTE3LTU1ZjMtNDhhZC04YmIxLTBlMWRjMjFlOTllMyJ9.nB5Pi1BiVrRmsirvfYVomMMMtQx64iKK33k39kWpyo0").forward(request,response);

        // response.sendRedirect("http://localhost:8091/oauth/authorize?client_id=client-a&response_type=code&scope=all&redirect_uri=http://baidu.com&Authorization=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJkZXYiLCJleHAiOjE2NzcxMzAxMzYsImlhdCI6MTY3NzEyOTEzNiwiYWNjb3VudCI6ImRldiIsImp0aSI6IjU1N2JhMTE3LTU1ZjMtNDhhZC04YmIxLTBlMWRjMjFlOTllMyJ9.nB5Pi1BiVrRmsirvfYVomMMMtQx64iKK33k39kWpyo0");
        response.getWriter().flush();
        response.getWriter().close();
    }

}
